package com.kamistoat.meimeichat.meimeichatserverapplication.netty.handlers;

import com.alibaba.fastjson.JSON;
import com.kamistoat.meimeichat.meimeichatserverapplication.netty.NettyServerBizHandler;
import com.kamistoat.meimeichat.meimeichatserverapplication.netty.service.NettyUserService;
import com.kamistoat.meimeichat.meimeichatserverapplication.netty.utils.NettyConstants;
import com.kamistoat.meimeichatserveraggrement.protocol.friend.AddFriendRequest;
import com.kamistoat.meimeichatserveraggrement.protocol.msg.MsgRoamingRequest;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.CompletableFuture;

/**
 * 收到消息漫游，保存消息即可
 */
@Component
@ChannelHandler.Sharable
public class MsgRoamingHandlerServer extends NettyServerBizHandler<MsgRoamingRequest> {
    @Autowired
    NettyUserService nettyUserService;

    /**
     * Warning:子类只需要重写该方法
     * 保存漫游消息，直接保存消息即可
     *
     * @param channel
     * @param msgRoamingRequest
     */
    @Override
    public void channelRead(Channel channel, MsgRoamingRequest msgRoamingRequest) {
        if(msgRoamingRequest == null) return;
        logger.info("接收用户 {} 与 用户 {} 间的消息漫游，保存消息...", msgRoamingRequest.getSenderId(), msgRoamingRequest.getReceiverId());
        // 这里用了异步去完成聊天消息入库。
        CompletableFuture<Void> asyncAppendChatRecord = nettyUserService.asyncAppendChatRecord(
                msgRoamingRequest.getSenderId(),
                msgRoamingRequest.getReceiverId(),
                msgRoamingRequest.getMsgText(),
                msgRoamingRequest.getMsgDate(),
                msgRoamingRequest.getMsgType(),
                NettyConstants.TalkType.Friend.getCode()
        );
        // 异步添加好友-自己的对话框. 因为能保证自己-好友的对话框一定存在，好友-自己的可能已经被好友删除或者压根不存在
        // 尤其是陌生人私聊的情况，更需要提前拉起对话框
        CompletableFuture<Void> asyncAppendTalkBox = nettyUserService.asyncAppendTalkBox(
                msgRoamingRequest.getReceiverId(),
                msgRoamingRequest.getSenderId(),
                NettyConstants.TalkType.Friend.getCode()
        );
    }
}
